package org.wang.generalcode.modules.exam.parser;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.wang.generalcode.modules.exam.listener.ExcelListener;
import org.wang.generalcode.modules.exam.pojo.entity.QuestionInfoEntity;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ExcelQuestionImportResult extends QuestionImportResult {
    private final Logger logger = LoggerFactory.getLogger(ExcelQuestionImportResult.class);

    public ExcelQuestionImportResult(InputStream inputStream) {
        super(inputStream);
    }

    public ExcelQuestionImportResult(MultipartFile file, HttpServletResponse response) throws IOException {
        super(file, response);
    }

    public ExcelQuestionImportResult(MultipartFile file) throws IOException {
        super(file);
    }

    @Override
    public void readTemplate() {
        try {

            MultipartFile file = super.getFile();

            // 定义读取监听器
            ExcelListener excelListener = new ExcelListener();

            // 使用EasyExcel读取Excel文件
            EasyExcel.read(file.getInputStream(), QuestionInfoEntity.class, excelListener)
                    .sheet()
                    .doRead();

            List<QuestionInfoEntity> successList = excelListener.getSuccessList();
            List<QuestionInfoEntity> failList = excelListener.getFailList();

            if (successList.isEmpty() && failList.isEmpty()) {
                super.setHasData(false);
                super.setErrorMsg("导入excel模板内容为空,请添加数据之后再导入");
            } else {
                super.setHasData(true);
                super.setErrorMsg(excelListener.getErrorMsg());
//                super.setErrorFileUrl("");
                super.setSuccessImportQuestionList(successList);
                super.setFailImportQuestionList(failList);
            }
        } catch (Exception e) {
            logger.error("模板数据解析异常", e);
        }
    }
}
